package com.gq.config;

import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jndi.JndiTemplate;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.gq" })
@MapperScan("com.gq.business.**.*mappers")
public class MvcConfig
{
    private Logger logger = LogManager.getLogger(this.getClass());
    
    @Bean
    public DataSource dataSource()
    {
        DataSource dataSource = null;
        JndiTemplate jndi = new JndiTemplate();
        try
        {
            dataSource = (DataSource) jndi.lookup("java:/comp/env/jdbc/TestDB");
        }
        catch (NamingException e)
        {
            logger.error("NamingException for +" + GlobalData.mysqljndinnamespace.getValue(), e);
        }
        return dataSource;
    }
    
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() throws Exception
    {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        return sessionFactory;
    }
    
    @Bean
    public DataSourceTransactionManager transactionManager()
    {
        return new DataSourceTransactionManager(dataSource());
    }
    
}
